package com.lexue.articlesync.config;

import com.lexue.articlesync.service.CacheService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 缓存清理定时任务
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "app.scheduler.enabled", havingValue = "true", matchIfMissing = true)
public class CacheCleanupScheduler {
    
    private final CacheService cacheService;
    
    /**
     * 每小时清理一次过期缓存
     */
    @Scheduled(fixedRateString = "${app.cache.cleanup-interval:3600}000")
    public void cleanupExpiredCache() {
        log.debug("开始清理过期文件缓存...");
        
        try {
            // 获取清理前的统计信息
            CacheService.CacheStats beforeStats = cacheService.getCacheStats();
            log.debug("清理前缓存统计: {}", beforeStats);
            
            // 执行清理
            cacheService.cleanExpiredFileCache();
            
            // 获取清理后的统计信息
            CacheService.CacheStats afterStats = cacheService.getCacheStats();
            log.info("缓存清理完成 - 清理前: {}个文件, 清理后: {}个文件", 
                    beforeStats.getTotalFiles(), afterStats.getTotalFiles());
            
        } catch (Exception e) {
            log.error("缓存清理任务执行失败", e);
        }
    }
    
    /**
     * 每天午夜进行一次完整的缓存统计和报告
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void dailyCacheReport() {
        try {
            CacheService.CacheStats stats = cacheService.getCacheStats();
            log.info("每日缓存报告: {}", stats);
            
            if (stats.getExpiredFiles() > 0) {
                log.info("发现 {} 个过期缓存文件，将在下次清理任务中删除", stats.getExpiredFiles());
            }
            
        } catch (Exception e) {
            log.error("生成每日缓存报告失败", e);
        }
    }
}